﻿using OpenTK.Graphics.OpenGL;

namespace Chimp.Core
{
    public class ChimpRenderTarget
    {
        public ChimpTexture2D Attached;

        static ChimpRenderTarget()
        {
            Bound = null;
        }

        public ChimpRenderTarget()
        {
            int buf = 0;
            GL.GenFramebuffers(1, out buf);
            Buffer = buf;
        }

        public static ChimpRenderTarget Bound { get; set; }
        public int Buffer { get; private set; }

        public void Bind()
        {
            if (Bound != null)
            {
                ChimpDebug.LogError(
                    "AttChimpt to bind more than one rendertarget at once, this is not yet supported on modern gpus.",
                    "XenoRenderTarget.Bind()");
            }
            Bound = this;
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, Buffer);
        }

        public void Unbind()
        {
            if (Bound != this)
            {
                ChimpDebug.LogError(
                    "AttChimpt to unbind unbound render target. This isn't support, and is quite silly. Go sit in the corner and think bout what you done. :) ",
                    "XenoRenderTarget.Unbind");
            }
            Bound = null;
            GL.BindFramebuffer(FramebufferTarget.Framebuffer, 0);
        }

        public void AttachTexture(ChimpTexture texture)
        {
            GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0,
                                    TextureTarget.Texture2D, texture.Texture, 0);
            CheckStatus();
            GL.Clear(ClearBufferMask.ColorBufferBit);
            Attached = texture as ChimpTexture2D;
        }

        public void AttachDepth(ChimpTexture texture)
        {
            GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment,
                                    TextureTarget.Texture2D, texture.Texture, 0);
            CheckStatus();
            GL.Clear(ClearBufferMask.DepthBufferBit);
        }

        public void CheckStatus()
        {
            FramebufferErrorCode ec = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer);
            if (ec != FramebufferErrorCode.FramebufferComplete)
            {
                ChimpDebug.LogError("FrameBuffer:  " + ec, "XenoRenderTarget.CheckStatus");
            }
        }
    }
}